﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFDemoMVVM.ViewModel
{
    public partial class PagingViewModel : ObservableObject
    {
        public PagingViewModel()
        {
            PageSizeOptions = new ObservableCollection<int> { 10, 20, 50 };
            PageSize = PageSizeOptions[0];
            CurrentPage = 1;
            Language = "zh-CN";
        }

        [ObservableProperty]
        private int currentPage;

        [ObservableProperty]
        private int pageSize;

        [ObservableProperty]
        private int totalItems;

        [ObservableProperty]
        private string language;

        [ObservableProperty]
        private ObservableCollection<int> pageSizeOptions;

        public int TotalPages => PageSize == 0 ? 1 : (int)Math.Ceiling((double)TotalItems / PageSize);
        public string PageStatus => Language == "zh-CN" ? $"第 {CurrentPage} / {TotalPages} 页" : $"page {CurrentPage} of {TotalPages}";

        // 每当这些属性改变时，通知依赖属性的更新
        partial void OnCurrentPageChanged(int value)
        {
            OnPropertyChanged(nameof(PageStatus));
        }

        partial void OnPageSizeChanged(int value)
        {
            CurrentPage = 1;
            OnPropertyChanged(nameof(TotalPages));
            OnPropertyChanged(nameof(PageStatus));
            GoToPage(CurrentPage);
        }

        partial void OnTotalItemsChanged(int value)
        {
            OnPropertyChanged(nameof(TotalPages));
            OnPropertyChanged(nameof(PageStatus));
        }

        partial void OnLanguageChanged(string value)
        {
            OnPropertyChanged(nameof(PageStatus));
        }

        [RelayCommand]
        private void FirstPage() => GoToPage(1);

        [RelayCommand]
        private void PrevPage() => GoToPage(Math.Max(1, CurrentPage - 1));

        [RelayCommand]
        private void NextPage() => GoToPage(Math.Min(TotalPages, CurrentPage + 1));

        [RelayCommand]
        private void LastPage() => GoToPage(TotalPages);

        private void GoToPage(int page)
        {
            CurrentPage = page;
            PageChanged?.Invoke(CurrentPage, PageSize);
        }

        public event Action<int, int> PageChanged;
    }

}
